<?php
declare (strict_types = 0);
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use app\model\CatModel;
use app\model\UserModel;
use app\Common;
use app\controller\Token;

//产品控制器
class Cat{

    //常用数据表内容 及常用字典
    var $cats=[];
    var $dept=[];
    var $users =[];
    var $status=array('1'=>'正常','2'=>'停用');
    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";         

    public function __construct(){
        //准备一个类型数组

        // $list = Db::table("cat")->select()->order('id')->toArray();
        // //$this->goodsType['0'] = array('id'=>0,'fid'=>0,'name'=>'无分类');
        // foreach($list as $k=>$v){
        //     $this->cats[$v['id']]=$v;
        // }
        $cm=new CatModel();
        $this->cats=$cm->catTree();

        $um=new UserModel();
        $this->users = $um->getAll();

    }

    //类别
    public function index(){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');
        
        $cm=new CatModel();
        $cats=$cm->catTree(); 

        foreach($cats as &$kv){
            $kv['fid_name'] = $this->cats[$kv['id']];                        
            $kv['status_name'] = $this->status[$kv['status']];
            $kv['creater_name'] = $this->users[$kv['creater']]['name'];
        }

        View::assign(['category'=>$this->cats,'data'=>$cats]);

        return View::fetch();
    }  

    //取得一个分类下面的子分类
    public function cat_list($id=0,$recusive=0){
        $all = Request::param();
        if(!empty($all['id'])){
            $id=$all['id'];
        }

        $list=Db::table('cat')->where('status',1);
        
        if($id){
            $list->where('fid',$id);
        }else{
            $list->where('fid','<',2);  //默认查出根节点和所有一级大类
        }
        
        $list = $list->order('sort')->column('id,name');
        
        if($recusive){
            foreach($list as &$row){
                $row['chs'] = $this->sub_cats($row['id'],1);
            }
        }

        return json($list);
    }

    private function sub_cats($id,$recusive=0){
        $list=Db::table('cat')->where('fid',$id)->where('status',1)->column('id,name');
        if($recusive){
            foreach($list as &$row){
                $row['chs']=Db::table('cat')->where('fid',$row['id'])->where('status',1)->column('id,name');
            }
        }
        return $list;

    }


    //分类编辑方法
    public function edit(){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login/target/admin');

        $all = Request::param();
        $id=$all['id'];
        $back = "<script>setTimeout(function(){history.back();},3000)</script>";        

        if(empty($id)) return 'Invalid cat id!'.$back ;
        if($id==1) $all['fid']=0;
        $cat = new CatModel();

        //传入内容,保存数据并跳转
        if($id>0 && !empty($all['name'])){
            $all['create_time'] = date('Y-m-d H:i:s');

            $exist = Db::query('select count(id) as count from cat where id<>'.$id." and name ='".trim($all['name'])."'");

            if($exist[0]['count']) return '分类名称已存在!'.trim($all['name']).$this->back ;

            //图片
            if($_FILES['file']['size']>0){
                $files =Common::upload();
                if($files['code']){
                    $all['img']=$files['msg'];
                }else{
                    return ($files['msg']);
                }
            }

            // //状态修改（禁用），子类，产品一起修改
            $old_cat = $cat->find($id);
            if($all['status']!=$old_cat['status']){
                $cats=[(int)$id];
                $res =$this->get_subCats_and_goods($id,$cats);
                $res =(json_decode($res->getContent(),true));

                if($res['code']==1){

                    $cats =implode(",", $res['cats']);
                    $goods =implode(",",$res['goods']);

                    $sql ="update cat set status=".$all['status']." where id in(".$cats.")";
                    Db::execute($sql);

                    if(count($res['goods'])){
                        $sql1 ="update goods set status=".$all['status']." where id in(".$goods.")";
                        Db::execute($sql1);                   
                    } 
                }
                //halt($sql,$sql1);
            }

            Db::table('cat')->save($all);

            header('location:/index.php/cat');
        }
        //不传内容只有id,查出本条数据 并进入编辑
        $row = $cat->find($id);

        View::assign(['category'=>$this->cats,'data'=>$row]);
        return View::fetch('edit');
    }

    public function del(){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login/target/admin');

        $all = Request::param();
        //halt($all['id']);
        if($all){
            return Common::row_del('cat',$all['id'],'分类');
        }
        return json(['code'=>0]);
    }

    //分类新增
    public function cat_add(){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login/target/admin');
           
                
        $all = Request::param();
        if($all){
            if(!empty($all['id'])) return '无效的操作!'.$back;     
            if(!$all['name']) return '无效的名称!'.$back;

            $cat = new CatModel();
            $row = $cat::where('name',$all['name'])->find();
            if(!empty($row)) return '分类已存在! ['. $all['name']."]".$back;

            $all['creater']  = Session::get('logonid');
            $all['create_time']  = date("Y-m-d H:i:s",time());

            $cat->insert($all);
            header("location:/index.php/cat");
        }
        View::assign(['category'=>$this->cats]);
        return View::fetch('cat_add');
    }

    //修改分类时候，检查一下子类及产品，提示
    public function get_subCats_and_goods(){
        $all = Request::param();
        if(empty($all['id'])) return json(['code'=>0,'msg'=>'what?']);
        $id = $all['id'];

        $cats=[(int)$id];
        $this->getSubCats($id,$cats);

        $goods = Db::query("select id from goods where cat_id in(".implode(",",$cats).")");
        $gs=[];
        foreach($goods as $g){
            $gs[]=$g['id'];
        }

        if(count($cats)==1 && !count($gs)) {
            return json(['code'=>0,'msg'=>'无子分类及相关的东西！']);
        }else{
            return json(['code'=>1,'msg'=>'ok','cats'=>$cats,'goods'=>$gs]);
        }

    }

     //递归取得子类
    public function getSubCats($id,&$arr=[]){
        foreach($this->cats as $d){
            if($d['fid']==$id){
                $arr[] = $d['id'];
                $this->getSubCats($d['id'],$arr);
            }
        }
        return $arr;
    }



    //从总部复制报价
    function fee_init(){
        $uid=Session::get('logonid');
        $all = Request::param();  
        if(empty($all['city'])) return json(['code'=>0,'msg'=>'请选择城市，以生成初始报价！']);

        $list=Db::table('fee')->where('city',$all['city'])->select()->toArray();
        if(count($list)) return json(['code'=>0,'msg'=>'城市报价已存在，不能重新生成！']);

        $list=Db::table('fee')->where('city',0)->select()->toArray();
        foreach($list as &$row){
            unset($row['id']);
            $row['city']=$all['city'];
            $row['create_time']=date('Y-m-d H:i:s');
            $row['creater']=$uid;
        }
        $res = Db::table('fee')->insertAll($list);

        return json(['code'=>1,'msg'=>$res.'条报已生成！']);
    }


    //学费管理
    public function fee_setup(){
        
        $all = Request::param();     

        if(!empty($all['fee_setup'])){
            unset($all['fee_setup']);
            if(!empty($all['id']) && $all['price']==0 && $all['price1']==0){
                Db::execute("update fee set status=44 where id=?",[$all['id']]);
            }else{

                //图片
                if($_FILES['file']['size']>0){
                    $files =Common::upload();
                    if($files['code']){
                        $all['image']=$files['msg'];
                    }else{
                        return ($files['msg']);
                    }
                }
                
                Db::table('fee')->save($all);

            }
        }
        
        $provs=[];
        $prov='';
        $citys=[];
        $city='';
        $list = Db::table('fee'); 

        //dump($all);

        if(!empty($all['prov'])){
            $prov=$all['prov'];
            $citys=Db::table('city')->where('fid',$prov)->select()->toArray();
        }

        if(!empty($all['city'])){
            $city=$all['city'];
            $list->where('city',$all['city']);
        }else{
            $list->where('city',0);
        }

        $list=$list->where('status',1)->order('id')->select()->toArray();

        foreach($list as &$row){
            $row['city'] = $row['city']?Db::table('city')->find($row['city']):['id'=>'0','name'=>'公司总部'];
        }

        $provs=Db::table('city')->where('fid',0)->select()->toArray();

        View::assign(['data'=>$list,'citys'=>$citys,'provs'=>$provs,'prov'=>$prov,'city'=>$city]);
        return View::fetch('fee_setup');
    }



    //小程序
    public function fee_list(){
        $all = Request::param();
        // if(empty($all['token'])) return json(['code'=>0,'msg'=>'非法请求！']);

        // $token = new token();
        // $arr = $token->check_token($all['token']); 
        // //token error
        // if($arr['code']<1){
        //     return json($arr);
        // }

        $list = Db::table('fee')->where('status',1)->where('type',1);
        if(!empty($all['area'])){
            $city=Db::table('city')->where('name','like','%'.$all['area'].'%')->value('name');
            $list->where('city',$city);
        }else{
            $list->where('city',0);
        }

        $list = $list->order('id')->select()->toArray(); 


        return json(['code'=>1,'data'=>$list]);        
    }

    //缴费列表
    public function pay_list(){
        $uid = Session::get('logonid');
        //if(!$uid) return header('location:/index.php/login/target/admin');

        $sql = "select * from fee where city=0 and status<10 order by id";
        $list = Db::query($sql);

        foreach($list as &$kv){
            $kv['price'] =number_format($kv['price'],2);
        }

        View::assign(['pay_list'=>$list]);
        return View::fetch();

    }

    //学车活动内容编辑
    public function fee_detail(){
        $all = Request::param();
        if(empty($all['id'])) return json(['code'=>0,'msg'=>'error']);

        $fee = Db::table('fee')->find($all['id']);
        return json(['code'=>1,'data'=>$fee]);

    }  


}
